package com.thlws.java.proxy.dynamic_javassist;

import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.Proxy;
import javassist.util.proxy.ProxyFactory;

import java.lang.reflect.Method;

/**
 * @author HanleyTang
 * @date 2018-12-04
 */
public class JavassistProxy<T> {

    private T target;

    public JavassistProxy(T target) {
        this.target = target;
    }



    public T createProxyInstance(){

        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setSuperclass(target.getClass());

        proxyFactory.setHandler((self, thisMethod, proceed, args) -> {

            System.out.println("----------javassist调用前-----------");
            Object result = proceed.invoke(self,args);
            System.out.println("----------javassist调用后-----------");
            return result;
        });


        try {
            return (T)proxyFactory.createClass().newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return null;
    }




}
